/**
 * 绘制 map 主文件，mapTool 主体
 */
import mapMix from '../mixins/mapMix';
import { Group, Rect } from '../render/index';

export default class currentSprite extends mapMix {
	/**
	 * canvas 主画布
	 */
	public canvas: any;
	

	constructor() {
		super({
			id: 'tetris_currentSprite',
		});
		Group({ // 背景画布
			id: this.id,
			x: 0,
			y: 0,
			width: 0,
			height: 0,
		}).then(canvas => {
			this.canvas = canvas;
			if(this.mapConst.editor?.gameComp){
				this.mapConst.editor?.gameComp.gamePreview.add(this.canvas);
				this.initSpriteFN();
			}
		});
	}

	public initSpriteFN(){
		this.mapConst.spriteData = this.mapConst.nextSpriteData;
		this.mapConst.nextSpriteData = this.mapConst.getNextRectFN();
		this.mapConst.stepY = undefined;
		this.mapConst.stepX = undefined;
		this.mapConst.moveTime = 300;
		this.drawSpriteFN();
		this.mapConst.integralFN();
	}
	
	public drawSpriteFN(){
		const spriteData = this.mapConst.spriteData.sprite[this.mapConst.spriteData.index];
		this.canvas.destroyChildren();
		this.moveSprite();
		
		for (let index = 0; index < spriteData.length; index++) {
		
			const element = spriteData[index];
			const y = index * this.mapConst.rectsize;
			
			for (let indexS = 0; indexS < element.length; indexS++) {
	
				const elementS = element[indexS];
				const x = this.mapConst.rectsize * indexS;
	
				if(elementS === 1){
					Rect({
						x: x,
						y: y,
						width: this.mapConst.rectsize - 1,
						height: this.mapConst.rectsize - 1,
						fill: '#dddddd'
					}).then(previewIcon => {
						this.canvas.add(previewIcon);
					});
				}
			}
		}
	}

	public moveSprite(){
		const spriteData = this.mapConst.spriteData.sprite[this.mapConst.spriteData.index];
		const stepH = spriteData.length;
		const stepW = spriteData[0].length;
		if(this.mapConst.stepX === undefined){
			this.mapConst.stepX = Math.floor((this.mapConst.gridW - stepW) / 2);
		}
		if(this.mapConst.stepY === undefined){
			this.mapConst.stepY = -stepH;
		}
		this.canvas.width(stepW * this.mapConst.rectsize);
		this.canvas.height(stepH * this.mapConst.rectsize);
		this.canvas.x(this.mapConst.stepX * this.mapConst.rectsize);
		this.canvas.y(this.mapConst.stepY * this.mapConst.rectsize);
	}

}
